package les.anagrama.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

import les.anagrama.R;
import android.content.Context;

public class Dictionary {
	@SuppressWarnings("unchecked")
	private Set<Word> dic[] = new Set[3];

	private static Dictionary instance;

	private Dictionary(Context ctx) {
		for (int i = 0; i < dic.length; i++) {
			dic[i] = new HashSet<Word>();
		}
		readFile(ctx);
	}

	public static Dictionary getInstance(Context ctx) {
		if (instance == null) {
			instance = new Dictionary(ctx);
		}
		return instance;
	}

	public Word getWord(Level level) {
		Word words[] = new Word[dic[level.ordinal()].size()];
		dic[level.ordinal()].toArray(words);
		return words[(new Random()).nextInt(dic[level.ordinal()].size())];
	}

	public boolean contains(Word word) {
		return dic[word.getLevel().ordinal()].contains(word);
	}

	private void readFile(Context ctx) {
		BufferedReader br = new BufferedReader(new InputStreamReader(ctx
				.getResources().openRawResource(R.raw.dic)));

		try {
			String w = br.readLine();
			do {
				String[] line = w.split(":");
				Word word = new Word(line[0], Integer.parseInt(line[1]),
						Level.values()[Integer.parseInt(line[2])-1]);
				dic[word.getLevel().ordinal()].add(word);
				w = br.readLine();
			} while (w != null);
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
